package cn.edu.ctgu.geo.wei.test;

import cn.edu.ctgu.geo.type.CalculationResult;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 计算经纬度范围对应的正方体高度范围
 */
public class CubeHeightCalculator {
    // 1度纬度对应的米数(赤道附近)
    private static final double METERS_PER_DEGREE_LAT = 111320;
    
    /**
     * 计算给定经纬度范围对应的正方体高度范围
     * @param minLng 最小经度(度)
     * @param maxLng 最大经度(度)
     * @param minLat 最小纬度(度)
     * @param maxLat 最大纬度(度)
     * @return 计算结果
     */
    public static CalculationResult calculateCubeHeightRange(
            double minLng, double maxLng, double minLat, double maxLat) {
        
        // 计算经纬度差
        double deltaLng = maxLng - minLng;
        double deltaLat = maxLat - minLat;
        
        // 计算中心纬度(用于校正经度距离)
        double centerLat = (minLat + maxLat) / 2;
        
        // 计算纬度方向距离(米)
        double latitudeDistance = deltaLat * METERS_PER_DEGREE_LAT;
        
        // 计算经度方向距离(米)，考虑纬度校正
        double longitudeDistance = deltaLng * METERS_PER_DEGREE_LAT * 
                Math.cos(Math.toRadians(centerLat));
        
        // 正方体边长取最小距离(确保正方体)
        double cubeSideLength = Math.min(longitudeDistance, latitudeDistance);
        
        // 计算两种高度范围方案
        double minHeightFromGround = 0;
        double maxHeightFromGround = cubeSideLength;
        double minHeightCentered = -cubeSideLength / 2;
        double maxHeightCentered = cubeSideLength / 2;
        
        // 保留两位小数提高可读性
        cubeSideLength = round(cubeSideLength, 2);
        longitudeDistance = round(longitudeDistance, 2);
        latitudeDistance = round(latitudeDistance, 2);
        
        return new CalculationResult(
                longitudeDistance, 
                latitudeDistance, 
                cubeSideLength,
                minHeightFromGround,
                maxHeightFromGround
        );
    }
    
    /**
     * 四舍五入保留指定小数位数
     */
    private static double round(double value, int decimalPlaces) {
        return new BigDecimal(value)
                .setScale(decimalPlaces, RoundingMode.HALF_UP)
                .doubleValue();
    }
    
    public static void main(String[] args) {
        // 输入给定的经纬度范围
        double minLng = 116.31222222;
        double maxLng = 116.31277778;
        double minLat = 39.99222222;
        double maxLat = 39.99277777;
        
        // 计算结果
        CalculationResult result = calculateCubeHeightRange(minLng, maxLng, minLat, maxLat);
        
        // 输出结果
        System.out.println("经纬度范围分析:");
        System.out.println("经度范围: " + minLng + " ~ " + maxLng + " °");
        System.out.println("纬度范围: " + minLat + " ~ " + maxLat + " °");
        System.out.println("------------------------");
        System.out.println(result.toString());
    }
}
    